package wyq.gy;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVGeoPoint;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import wyq.gy.Bean.robOrderMsg;
import wyq.gy.fragment.InfoDialogFragment;
import wyq.gy.fragment.TipsDialogFragment;
import wyq.gy.lib.ActivityList;
import wyq.gy.lib.Constants;
import wyq.gy.lib.LocationTask;
import wyq.gy.lib.OnLocationGetListener;
import wyq.gy.lib.PositionEntity;
import wyq.gy.service.PollingService;
import wyq.gy.service.PollingUtils;
import wyq.gy.service.ServiceOne;
import wyq.gy.service.ServiceTwo;

import static wyq.gy.lib.Constants.isDialogShow;


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
        AMap.OnCameraChangeListener,
        AMap.OnMapLoadedListener, OnLocationGetListener, View.OnClickListener {
    private static final String TAG = "MainActivity";
    MapView mMapView = null;
    private AMap mAmap;
    private Marker mPositionMark;
    private LocationTask mLocationTask;
    private ImageView mLocationImage;
    private double m_latitue;
    private double m_longitude;
    private boolean isFirst = true;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_main);
        init(savedInstanceState);
        ActivityList.getInstance().addActivity(this);
        InitView();
        InitService();

    }

    private void InitView(){
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(R.string.app_name);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View headerLayout = navigationView.getHeaderView(0);//R.layout.nav_header_main);
        TextView username_tx = (TextView)headerLayout.findViewById(R.id.app_user_name);
        username_tx.setText(AVUser.getCurrentUser().getString("Name"));
    }


    private void init(Bundle savedInstanceState) {
        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        mAmap = mMapView.getMap();
        mAmap.getUiSettings().setZoomControlsEnabled(true);
        mAmap.setOnMapLoadedListener(this);
        mAmap.setOnCameraChangeListener(this);
        mLocationImage = (ImageView) findViewById(R.id.location_image);
        mLocationImage.setOnClickListener(this);
        Button mapBtn = (Button) findViewById(R.id.map_btn);
        mapBtn.setOnClickListener(this);
        mAmap.getUiSettings().setRotateGesturesEnabled(false);
        mAmap.getUiSettings().setMyLocationButtonEnabled(false);//设置默认定位按钮是否显示，非必需设置
        mAmap.setMyLocationEnabled(false);// 设置为true表示系统定位按钮显示并响应点击，false表示隐藏，默认是false
        mLocationTask = LocationTask.getInstance(getApplicationContext());
        mLocationTask.setOnLocationGetListener(this);
        mLocationTask.startLocate();
       // sHA1(this);
    }

    private void GetNearWorker(double latitue, double longitude){
        AVQuery<AVUser> query = new AVQuery<>("_User");
        AVGeoPoint point = new AVGeoPoint(latitue, longitude);
        query.limit(30);
        query.whereNear("RegCoordinate", point);
        query.findInBackground(new FindCallback<AVUser>() {
            @Override
            public void done(List<AVUser> workers, AVException e) {
                if(workers != null) {
                    for (int i = 0; i < workers.size(); i++) {
                        AVGeoPoint geo = (AVGeoPoint) workers.get(i).get("RegCoordinate");
                        mAmap.addMarker(new MarkerOptions().position(new LatLng(geo.getLatitude(), geo.getLongitude()))
                                .anchor(0.8f, 0.8f)
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.work)));
                    }
                }
            }
        });
    }

    //删除指定Marker
    private void clearMarkers() {
        //获取地图上所有Marker
        List<Marker> mapScreenMarkers = mAmap.getMapScreenMarkers();
        for (int i = 0; i < mapScreenMarkers.size(); i++) {
            if(!mapScreenMarkers.get(i).equals(mPositionMark)) {
                Marker markerer = mapScreenMarkers.get(i);
                markerer.remove();//移除当前Marker
            }
        }
        //mAmap.invalidate();//刷新地图
    }



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_msg) {
            return true;
        }else if(id == R.id.action_fankui){
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, SuggestionActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.undone_order) {
            // Handle the camera action
            Intent intent = new Intent();
            intent.putExtra("state","1");
            intent.setClass(MainActivity.this, HistoryOrderActivity.class);
            startActivity(intent);
//        } else if (id == R.id.my_team) {

//        } else if (id == R.id.order_record) {
//            Intent intent = new Intent();
//            intent.putExtra("state","4");
//            intent.setClass(MainActivity.this, HistoryOrderActivity.class);
//            startActivity(intent);
        } else if (id == R.id.nav_manage) {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, SettingActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, SuggestionActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //地图
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }
    @Override
    public void onMapLoaded() {
        addMarkerInScreenCenter();
    }

    private void addMarkerInScreenCenter() {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.anchor(0.5f, 0.5f);
        markerOptions.position(new LatLng(0, 0));
        markerOptions
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(),
                                R.drawable.map_pin)));
        mPositionMark = mAmap.addMarker(markerOptions);

        mPositionMark.setPositionByPixels(mMapView.getWidth() / 2,
                mMapView.getHeight() / 2);
        mLocationTask.startLocate();
    }

    @Override
    public void onCameraChange(CameraPosition arg0) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if (isNetworkAvailable(this)) {
            clearMarkers();
            GetNearWorker(cameraPosition.target.latitude, cameraPosition.target.longitude);
        }else
        {
            Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
        }
    }

    //定位ok
    @Override
    public void onLocationGet(PositionEntity entity) {
        m_latitue = entity.latitue;
        m_longitude = entity.longitude;
        if(isFirst){
            LatLng position = new LatLng(m_latitue, m_longitude);
            CameraUpdate cameraUpate = CameraUpdateFactory.newLatLngZoom(
                    position, mAmap.getCameraPosition().zoom);
            mAmap.animateCamera(cameraUpate);
            isFirst = false;
        }
    }

    @Override
    public void onRegecodeGet(PositionEntity entity) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.location_image:
                LatLng position = new LatLng(m_latitue, m_longitude);
                CameraUpdate cameraUpate = CameraUpdateFactory.newLatLngZoom(
                        position, mAmap.getCameraPosition().zoom);
                mAmap.animateCamera(cameraUpate);
                break;
            case R.id.map_btn:
                TipsDialogFragment dialog = new TipsDialogFragment();
                dialog.show(getFragmentManager(), "TipsDialogFragment");
                break;
        }
    }

    public boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result=hexString.toString();
            Log.i("result", result);
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static boolean isServiceWorked(Context context, String serviceName) {
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    private void InitService() {
        Intent serviceOne = new Intent();
        serviceOne.setClass(MainActivity.this, ServiceOne.class);
        startService(serviceOne);
        PollingUtils.startPollingService(this, Constants.POLLINGTime, PollingService.class, PollingService.ACTION);
        Intent serviceTwo = new Intent();
        serviceTwo.setClass(MainActivity.this, ServiceTwo.class);
        startService(serviceTwo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(robOrderMsg msg) {
        Log.e(TAG, "on recv BroadMsg");
        if(isDialogShow == false) {
            InfoDialogFragment dialog = new InfoDialogFragment();
            dialog.SetData(msg);
            dialog.show(getFragmentManager(), "InfoDialogFragment");
            isDialogShow = true;
        }
    };

    @Subscribe
    public void handleSomethingElse(robOrderMsg msg) {
        Log.e(TAG, "handleSomethingElse");
        if(isDialogShow) {
            InfoDialogFragment dialog = new InfoDialogFragment();
            dialog.SetData(msg);
            dialog.show(getFragmentManager(), "InfoDialogFragment");
            isDialogShow = true;
        }
    }
}
